/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  themes_default
 */

/**
 * jQuery scripts for back office
 */

function clearLogs()
{
	$.getScript("?module=backoffice&action=AjaxClearLogs", function(value){
        infoMessage(value);
        refreshRightCol();
      });
}

/***************************************************************************
 * 
 * 					PAGE EDITION
 *
 ***************************************************************************/

function displayPageSaveLayout()
{
    if($('#saveButtonSubMenu').is(':visible'))
    {
        $('#saveButtonSubMenu').hide();
    }
    else
    {
        $('#saveButtonSubMenu').show();
    }
}

/**
 * Switch page status to PUBLISHED/DRAFT
 * @param {integer} pageId
 * @param {string} pageLang
 */
function switchPageStatus(pageId, pageLang)
{
    $.ajax({
        url: '?module=website&action=AjaxSwitchPageStatus',
        data: {docId:pageId,docLang:pageLang},
        success: function(resp)
        {
            if(resp == 'success')
            {
                $.historyLoad(getHash(document.location.toString()), {refresh: true});
            }
            else
            {
                // @todo : launch a modal !
                res = resp.split('/');
                showModal('?module=website&action=block_modal_SwitchPage&docId='+pageId+'&docLang='+pageLang+resp);
            }
        }
    });
}

/**
 * Get a locale value from a local file in modules
 */
function getLocale(key, params ,lang)
{
    var result;

    $.ajax({
            url: '?module=backoffice&action=AjaxGetLocale',
            data: {key:key, lang:lang, params:params},
            async: false,
            success: function(res)
            {
                result = res;
            }
    });

    return result;
}

/**
 * Save page modifications to page
 * @param {Integer} pageId
 * @param {string} pageLang
 */
function savePageModifications(pageId, pageLang)
{
	$.ajax({
        url: '?module=backoffice&action=AjaxPublishTempDocument',
        data: {documentId:pageId, documentLang:pageLang},
        complete : function(){
            reloadSlideMenuContent(document.location.href);
            loadRightColContent(getHash(document.location.href), true);
            infoMessage(getLocale('website.locales.savedModifications'));
        }
    });
}

/**
 * Undo page modifications
 * @param {Integer} pageId
 * @param {String} pageLang
 */
function undoModifications(pageId, pageLang)
{    
    if($('#undoModifications').hasClass('active'))
    {
        $.ajax({
            url: '?module=website&action=AjaxDeleteTempPage',
            data: {pageId:pageId, pageLang:pageLang},
            complete: function(){
                reloadSlideMenuContent(document.location.href);                
                loadRightColContent(getHash(document.location.href), true);
                infoMessage(getLocale('website.locales.canceledModifications'));
            }
        });
    }
}

/*
function previewRevision(documentId, documentLang)
{
	revision = $("#revisions").find("option:selected").val();
	centeredPopup("../index.php?module=website&action=Preview&pageId="+documentId+"&pageLang="+documentLang+"&revision="+revision, "preview", 1024, 768);
}

function loadRevision(pageId, documentLang)
{
	revision = $("#revisions").find("option:selected").val();
	if($("div#saveButton").css("display") == "block")
	{
		if(confirm("Annuler les modifications et restaurer la révision "+revision+" pour édition ?"))
		{
			publishPage(pageId, revision, documentLang, "false");
		}
	}
	else
	{
		if(confirm("Restaurer la révision "+revision+" pour édition ?"))
		{
			publishPage(pageId, revision, documentLang, "false");
		}
	}
}
*/

/**
 * Open a centered popup
 * @param {String} windowURL
 * @param {String} windowName
 * @param {Integer} windowWidth
 * @param {Integer} windowHeight
 * @param {Boolean} hasScrollbars
 * @param {Boolean} isResizable
 * @param {Boolean} hasMenubar
 * @param {Boolean} hasToolbar
 * @param {Boolean} hasAddressbar
 * @param {Boolean} hasStatusbar
 * @param {Boolean} isFullscreen
 */
function centeredPopup(windowURL, windowName, windowWidth, windowHeight, hasScrollbars, isResizable, hasMenubar, hasToolbar, hasAddressbar, hasStatusbar, isFullscreen) 
{
    var windowLeft = (screen.width - windowWidth) / 2;
    var windowTop = (screen.height - windowHeight) / 2;
    var windowProperties = 'height=' + windowHeight + ',width=' + windowWidth + ',top=' + windowTop + ',left=' + windowLeft + ',scrollbars=' + hasScrollbars + ',resizable=' + isResizable + ',menubar=' + hasMenubar + ',toolbar=' + hasToolbar + ',location=' + hasAddressbar + ',statusbar=' + hasStatusbar + ',fullscreen=' + isFullscreen + '';
    var objwindow = window.open(windowURL, windowName, windowProperties)
    if (parseInt(navigator.appVersion) >= 4)
    {
      objwindow.window.focus();
    }

    return objwindow;
}

/**
 * Activate the submit button when a field is modified in a page edition
 * 
 * @param {String} origHref
 */
function activateSubmitButton(origHref)
{
	$("form input[type='text']").one("keydown", function(){	
		preventClickWoSaving();
	});
	
	$("form input[type='checkbox'][class!=select]").click(function(){	
		preventClickWoSaving();
	});
	
	$("form select").change(function(){
		preventClickWoSaving(); 
	});
	
	$("form textarea").one("keydown",function(){
		preventClickWoSaving(); 
	});
	
	$('.fileUpload').ajaxForm({
        target: '#right-col'
    });
	
	$('form:not(.ajaxForm,.fileUpload,.formRedirect)').submit(function(event)
	{
		event.preventDefault();
		tinyMCE.triggerSave();

        var form = $(this);

		$.ajax({
   			type: "post",
  		 	url: $(this).attr("action"),
   			data: $(this).serialize(),
            success: function(resp){;
                if(resp.search("redirectUrl=") != -1)
                {
                    ajaxHref = resp.replace(/^.*redirectUrl=/, '');
                    slideMenuToUp(ajaxHref);
                }
                else
                {
                    if(resp != "")
                    {
                        parentDiv = form.parent("div").attr("id");
                        if(resp.search(parentDiv) != -1)
                        {
                            $("#"+parentDiv).replaceWith(resp);
                        }
                        else
                        {
                            $("#"+parentDiv).html(resp);
                        }
                        
                        if($("#formStatus").html() != "failed")
                        {
                            if($("#formStatus").html() == 'refresh')
                            {
                                location.reload(true);
                            }
                            else
                            {
                                $('submitButton').slideUp('normal', formSuccess(origHref));
                            }
                        }
                        else
                        {
                            activateSubmitButton(origHref);
                        }
                    }
                    else
                    {
                        $('submitButton').slideUp('normal', formSuccess(origHref));
                    }
                }
            }
	 		});
	});
}

/**
 * Catch .ajaxForm submit
 */
function formAjax()
{
	$('form[class=ajaxForm]').submit(function(event){
		infoMessage(getLocale('website.locales.datasSaved'));
		event.preventDefault();	
		
		tinyMCE.triggerSave();
		
		resp = $.ajax({
   			type: "post",
  		 	url: $(this).attr("action"),
   			data: $(this).serialize(),
			async: false
	 		}).responseText;
		
		$(this).parent("div").html(resp);
		activatePageModificationsButtons();
		
		formAjax();
	});
}

function preventClickWoSaving()
{
	$("div.submitButton").slideDown("normal");
    $('button[type=reset]').click(function(){
        $("div.submitButton").slideUp("normal");
        activateSubmitButton(document.location.toString);
    });
}

/**
 * Action loaded when div #success is present after a form submission
 * @param origHref - set to "currentPage" to reload current page
 * @return void
 */
function formSuccess(origHref)
{		
	if(origHref == "currentPage" || origHref == "reloadMenu")
	{
		relayTo = getHash(document.location.toString());
	}
	else
	{
		relayTo = origHref
	}
	
	if(origHref != "reloadMenu")
	{
		loadRightColContent(relayTo, false);
	}
	
	reloadSlideMenuContent(relayTo);
    infoMessage(getLocale('website.locales.datasSaved'));
}

function activatePageModificationsButtons()
{
    if(!$('a.switch').hasClass('active'))
    {
        $('a.switch').addClass('active');
        $('.saveButtonRight button').addClass('active').removeAttr('disabled');
        $('.saveButtonLabel').html('<img src="/themes/default/backend/medias/icons/1616/status/VALIDATION_big.png" class="icon16" alt="" title=""> à valider');
        reloadSlideMenuContent(document.location.href);
    }
}

function deactivatePageModificationsButtons()
{
    $('a.switch').removeClass('active');
    $('.saveButtonRight button').removeClass('active').attr('disabled', 'disabled');
}

/***************************************************************************
 *
 * 					BLOCKS MENU
 *
 ***************************************************************************/

function displayBlockBar()
{
    if(!$('#blockPanel').is(':visible'))
    {
        $.ajax({
            url: '?module=website&action=block_AjaxGetBlocksModules',
            success: function(value)
            {
                if(!$('#blockPanelModulesWrapper').html())
                {
                    $('body').append('<div id="blockPanelModulesWrapper" style="position:absolute;float:left;width:auto;"></div>');
                    $('#blockPanelModulesWrapper').html(value);
                    $('.blockPanelModulesCat').html(value).width($('#blockPanelModulesWrapper').width());
                }
            },
            complete: function()
            {
                $('#blockPanelModulesWrapper').remove();
                
                $('.blockPanelModulesCatContainer').width($('#saveButton').width()-300);
                $('#blockPanel').show('fast', function(){

                    if( $('.blockPanelModulesCat').width() > $('.blockPanelModulesCatContainer').width())
                    {
                        $('.blockPanelSlide').show();
                    }

                    blockPanelSlideRight($('.blockPanelModulesCat').width());
                    blockPanelSlideLeft($('.blockPanelModulesCat').width());

                    getModuleBlocks();

                    resizeBlockBar();
                });
            }
        });
    }
}

function hideBlockBar()
{
    $('.blockPanelBlocks').slideUp();
    $('#blockPanel').slideUp();
}

function getModuleBlocks()
{
    $('.blockPanelModulesCat a').click(function(event){

       event.preventDefault();

       var moduleName = $(this).attr('href');
       var link = $(this);

       $.ajax({
           url: '?module=website&action=block_AjaxGetBlocks',
           data: {moduleName:moduleName},
           success: function(value)
            {
                if(!$('#blockDndWrapper').html())
                {
                    $('body').append('<div id="blockDndWrapper"></div>');
                    $('#blockDndWrapper').html(value);
                    $('.dndBlocks').width(($('#blockDndWrapper dl.block').size()) * 152).css('marginLeft', '0').html(value);
                }
                
            },
            complete: function()
            {
                $('.blockPanelBlocks').slideDown();
                $('.dndBlocksContainer').width((Math.floor(($('#blockPanel').width()-263) / 152)) * 152);
                
                var nbPages = Math.ceil(($('#blockDndWrapper dl.block').size() * 152) / $('.dndBlocksContainer').width());

                if($('.dndBlocks').width() <= $('.dndBlocksContainer').width())
                {
                    $('.blocksSlider').hide();
                }
                else
                {
                    $('.blocksSlider').show();
                    $('#currentBlocksPage').text('1');
                    $('.blocksSlideLeft').addClass('inactive');
                    $('.blocksSlideRight').show();
                    $('#nbBlocksPages').text(nbPages);
                    blocksSlideRight($('#blockDndWrapper').width(), nbPages);
                    blocksSlideLeft($('#blockDndWrapper').width(), nbPages);
                }
                $('#blockDndWrapper').remove();
                $('.blockPanelModulesCat a.selectedModTab').removeClass('selectedModTab');
                
                link.addClass('selectedModTab');
                dragNdropBlocks($('#pageId').text(), $('#pageLang').text());
            }
       });
    });
}

function resizeBlockBar()
{
    $(window).resize(function(){
        if($('.blockPanelBlocks').is(':visible'))
        {
            var blocksPerPage = Math.floor(($('#blockPanel').width()-263) / 152);
            $('.dndBlocksContainer').width(blocksPerPage * 152);
            
            var nbPages = Math.ceil(($('#blockPanel dl.block').size() * 152) / $('.dndBlocksContainer').width());
            var currentPage = parseInt($('#currentBlocksPage').text());

            if(currentPage > nbPages) currentPage = nbPages;

            $('.dndBlocks').css('marginLeft', -((currentPage-1) * (blocksPerPage * 152)) + 'px');

            $('#nbBlocksPages').text(nbPages);
            $('#currentBlocksPage').text(currentPage);

            if(parseInt($('#currentBlocksPage').text()) == nbPages)
            {
                $('.blocksSlideRight').hide();
            }
            else
            {
                $('.blocksSlideRight').show();
            }
            
            blocksSlideRight(blocksPerPage * 152, nbPages);
            blocksSlideLeft(blocksPerPage * 152, nbPages);
        }

        $('.blockPanelModulesCat').css('marginLeft', '0');
        $('.blockPanelModulesCatContainer').width($('#blockPanel').width()-300);

        if($('.blockPanelModulesCat').width() < ($('#blockPanel').width()-300))
        {
            $('.blockPanelSlide').hide();
        }
        else
        {
            $('.blockPanelModulesCatContainer').width($('#blockPanel').width()-300);
            $('.blockPanelSlide').show();
            $('.blockPanelSlideLeft').addClass('inactive');
            $('.blockPanelSlideRight').removeClass('inactive');
            blockPanelSlideRight($('.blockPanelModulesCat').width());
            blockPanelSlideLeft($('.blockPanelModulesCat').width());
        }
    });
}

function blocksSlideRight(wrapperWidth, nbPages)
{
    $('.blocksSlideRight').unbind('click');
    $('.blocksSlideRight').click(function(event){
        event.preventDefault();

        if(parseInt($('#currentBlocksPage').text()) < nbPages)
        {
            $('#currentBlocksPage').text(parseInt($('#currentBlocksPage').text()) + 1);
            $(this).unbind('click');

            if(parseInt($('#currentBlocksPage').text()) == nbPages)
            {
                $('.blocksSlideRight').hide();
                $('.blocksSlideLeft').removeClass('inactive');
            }
            else
            {
                $('.blocksSlideRight').show();
                $('.blocksSlideLeft').removeClass('inactive');
            }

            $('.dndBlocks').animate({'marginLeft': '-='+$('.dndBlocksContainer').width()+'px'}, function(){
                blocksSlideRight(wrapperWidth, nbPages);
            });
        }
    });
}

function blocksSlideLeft(wrapperWidth, nbPages)
{
    $('.blocksSlideLeft').unbind('click');
    $('.blocksSlideLeft').click(function(event){
        event.preventDefault();

        if(parseInt($('#currentBlocksPage').text()) > 1)
        {
            $('#currentBlocksPage').text(parseInt($('#currentBlocksPage').text()) - 1);
            $(this).unbind('click');

            if(parseInt($('#currentBlocksPage').text()) == 1)
            {
                $('.blocksSlideLeft').addClass('inactive');
                $('.blocksSlideRight').show().removeClass('inactive');
            }
            else
            {
                $('.blocksSlideLeft').show();
                $('.blocksSlideRight').show();
            }

            $('.dndBlocks').animate({'marginLeft': '+='+$('.dndBlocksContainer').width()+'px'}, function(){
                blocksSlideLeft(wrapperWidth, nbPages);
            });
        }
    });
}

function blockPanelSlideRight(wrapperWidth)
{
    $('.blockPanelSlideRight').unbind('click');
    $('.blockPanelSlideRight').click(function(event){
        event.preventDefault();
        offset = Math.round((wrapperWidth - $('.blockPanelModulesCatContainer').width()) /2);
        pos = $('.blockPanelModulesCat').css('marginLeft').substring(0, $('.blockPanelModulesCat').css('marginLeft').indexOf("px"));

        if(pos > -(offset) * 2)
        {
            $('.blockPanelSlideLeft').removeClass('inactive');
            if(-offset == pos)
            {
                $('.blockPanelSlideRight').addClass('inactive')
            }
            $(this).unbind('click');
            $('.blockPanelModulesCat').animate({'marginLeft': '-='+offset+'px'}, function(){
                blockPanelSlideRight(wrapperWidth);
            });
        }
    });
}

function blockPanelSlideLeft(wrapperWidth)
{
    $('.blockPanelSlideLeft').unbind('click');
    $('.blockPanelSlideLeft').click(function(event){
        event.preventDefault();
        offset = Math.round((wrapperWidth - $('.blockPanelModulesCatContainer').width()) /2);
        pos = $('.blockPanelModulesCat').css('marginLeft').substring(0, $('.blockPanelModulesCat').css('marginLeft').indexOf("px"));

        if(pos < 0)
        {
            $(this).unbind('click');

            $('.blockPanelSlideRight').removeClass('inactive')
            if(parseInt(pos) + offset == 0)
            {
                $('.blockPanelSlideLeft').addClass('inactive');
            }
            
            $('.blockPanelModulesCat').animate({'marginLeft': '+='+offset+'px'}, function(){
                blockPanelSlideLeft(wrapperWidth);
            });
        }
    });
}

/***************************************************************************
 *
 * 					BLOCKS DRAG AND DROP
 *
 ***************************************************************************/

function dragNdropBlocks(pageId, pageLang)
{
    var els = $(".freeContentZone").toArray();
    var check = serializeDndElements(els);
    var content = $('.dndBlocks').html();
    $('.dndBlocks dl').draggable({
            connectToSortable : '.freeContentZone',
            handle: 'dl',
            helper: 'clone',
            revert: false,
            zIndex: 100,
            start: function(e, ui) {},
            drag: function(e, ui)
            {
               $('.freeContentZone').attr('style','border: 1px solid #7EBF28 !important;');
            },
            stop: function(e, ui)
            {
                $(".dndBlocks dl").disableSelection();
            }
    });
}

function dragAndDropPageBlocks(pageId, pageLang)
{
    var els = $(".freeContentZone").toArray();
    var check = serializeDndElements(els);
    var result = '';

    $('.freeContentZone').sortable({
        items: 'dl',
        handle: 'dt',
        connectWith: ['.freeContentZone'] ,
        tolerance: "pointer",
        appendTo: "body",
        scroll: false,
        start: function(e, ui) {
            ui.helper.addClass('ui-helper-shadow');
            ui.helper.children('dt').children('.blockEditButtons').hide();
            ui.helper.width(ui.item.width());            
            $('#pageStructureEdit .freeContentZone').attr('style','border: 1px solid #7EBF28 !important;');
        },
        change: function(e, ui){
            ui.helper.width(ui.placeholder.width());
            ui.placeholder.attr('style','background:#7EBF28 !important;height:25px;');
        },
        beforeStop: function(e, ui)
        {
            ui.helper.children('dt').children('.blockEditButtons').show();
            ui.helper.removeClass('ui-helper-shadow');
        },
        stop: function(e, ui){
            result = serializeDndElements(els);

            $('.freeContentZone').removeAttr('style');

            if($('#unused dl').length == 0) {$('#unused').remove()};

            if(check != result)
            {
                if(ui.item.attr('id') == '')
                {
                    $.post("?module=website&action=AjaxNextBlockId", {pageId:pageId, pageLang:pageLang}, function(data){
                        var blockId = data;
                        ui.item.attr({id:"block_"+blockId});
                        $.ajax({
                                url:'?module=backoffice&action=AjaxGetBlockButtons',
                                data: {blockId: blockId, docId: pageId, docLang: pageLang, blockParams: ui.item.find("dd.rawValues").html()},
                                success: function(buttons){
                                    ui.item.find("dt:first").prepend(buttons);

                                    ui.item.find("div>a").click(function(event){
                                        showModal("?module=backoffice&action=AjaxContext&href="+getHash(this.href));
                                        return false;
                                    });

                                    ui.item.find("dd.rawValues").prepend('blockId="'+blockId+'" ');
                                    ui.item.find("dt>span").attr("id", "editable_"+pageId+"_"+blockId).addClass("editable");

                                    $.ajax({
                                        url: '?module=website&action=AjaxAddBlock',
                                        data: {value: ui.item.children("dd.rawValues").html(), pageId:pageId, pageLang: pageLang},
                                        success: function(value){
                                            result = serializeDndElements(els);
                                            $.post("?module=website&action=AjaxSaveStructure&" + result, {
                                                pageId: pageId, pageLang: pageLang
                                            });
                                        }
                                    });
                                }
                            });
                    });
                }
                else
                {
                    $.post("?module=website&action=AjaxSaveStructure&" + result, {
                        pageId: pageId, pageLang: pageLang
                    });
                }
               
                activatePageModificationsButtons();
            }
        }
	});
}

function serializeDndElements(els)
{
    var result = '';
    $.each(els, function(i, freeZone) {
        $.each($("#"+freeZone.id+" .block").toArray(), function(i, block){
            result += freeZone.id + '[]=' + block.id + '&';
        });
    });
    return result.substr(0,result.length-1);
}

/**
 * Delete block in page
 * 
 * @param pageId
 * @param pageLang
 * @param blockId
 */
function deleteBlock(pageId, pageLang, blockId)
{
	$.ajax({
		type: 'post',
		url: '?module=website&action=AjaxDeleteBlock',
		data: {docId: pageId, docLang: pageLang, blockId: blockId},
		complete: function()
		{
			$("#block_"+blockId).slideUp("normal", function(){
				$(this).remove();
                activatePageModificationsButtons();
			});
		}
	})	
}

/***************************************************************************
 * 
 * 					GENERAL BACK-OFFICE
 * 
 ***************************************************************************/

/**
 * Display an information message in the top bar
 * @param {String} message
 */
function infoMessage(message)
{
	$('div#message').html(message).css('margin-left', '-'+($("div#message").width()/2)+"px").animate({"top": "0"}, "normal", function(){
        $("div#message").delay(2500).animate({"top": "-24px"}, "normal");
	});
}

/**
 * Loading back office page content
 * 
 * @param {String} href
 * @param {Array} options
 */
function loadContent(href, options)
{    
    params = getHash(href).split('/');
    
    $('#mainMenu a.selected').removeClass('selected');
    $('#mainMenu a').removeClass('before');

	if(params[1] != null)
	{
		$('#'+params[1]+'Link').addClass('selected');
        $('#'+params[1]+'Link').prev().addClass("before");
	}

    if(href != null)
    {
        if(options != null)
        {
            refresh = options.refresh != null ? options.refresh : false;

            if(refresh == false)
            {
                loadOnlyRightCol = options.onlyLoadRightCol != null ? options.onlyLoadRightCol : false;
                loadInTab = options.loadInTab != null ? options.loadInTab : isLoadingInTab(href);
            }
            else
            {
                loadOnlyRightCol = false;
                loadInTab = false;
            }
        }
        else
        {
            loadOnlyRightCol = false;
            loadInTab = isLoadingInTab(href);
        }

        if(loadOnlyRightCol == true)
        {
            loadRightColContent(href, loadInTab);
        }
        else
        {
            // Load left menu content when only loading a new page
            if(loadInTab != true)
            {
				if(getHash(href) != '')
				{					
					loadLeftMenu(getHash(href));
				}
				else // load bo dashboard
				{
					$('#left-col').hide();
					$('#ajaxLoader').css('left', '0');
					$('#ajaxLoader #loaderPic').css('margin-left', '-90px');
					$('#right-col').css('padding-left', '0').addClass('homePanel');
				}
            }

            loadRightColContent(href, loadInTab);
        }
    }

     $('#leftMenuTitle').html($('#mainMenu a.selected').html());
}

/**
 * Open left column accordion by link
 * 
 * @param {String} href
 */
function loadLeftMenu(href)
{
	$.ajax({
		url: '?module=backoffice&action=block_sliderMenu',
        data: {href:href},
		success: function(html){
			$(".slide-menu-left").html(html);
            sliderMenu();
		}
	});
}

/**
 * Check if current page must be loaded in a tab or not
 * 
 * @param {String} href
 * @param {boolean} forceReload
 * @return boolean
 */
function isLoadingInTab(href, forceReload)
{
	var tabbed = false;

	// If content is not forced to reload completely
	if(forceReload != true)
	{		
		// and tabContent is empty
		if($("#tabContent").html() == null)
		{
			tabbed = false;		
		}
		else
		{
            $.ajax({
                url: '?module=backoffice&action=AjaxCheckTab',
                data: {href:getHash(href)},
                async: false,
                success: function(msg){
                    if(msg == 'true')
                    {
                        tabbed = true;
                    }
                }
            });
		}		
	}

	return tabbed;
}

/**
 * Load right column content
 * 
 * @param {string} href
 * @param {boolean} loadInTab
 */
function loadRightColContent(href, loadInTab)
{
	ajaxHref = getHash(href);

    if(!checkSession()) return void(0);

	if(loadInTab == false)
	{
		$("#ajaxLoader").show();
	}
	else
	{
		$("#ajaxTabLoader").show();
	}	

	$.ajax({											// Load right column content
  		url: '?module=backoffice&action=AjaxController',
        data: {href: ajaxHref, tabbed: loadInTab},
  		success: function(html)							// After loading success display the content in the right place
		{
			if(loadInTab == true)						// if loaded content is a tab load into #tabContent
			{
                $("#tabContent").html(html);
			}
			else
			{		
				$.ajax({
					url: '?module=backoffice&action=block_contextMenu',
                    data: {href:ajaxHref},
                    async: false,
					success: function(html)
					{
                        $("#contextMenu").html(html);
					}
				});

				$("#right-col").html(html);				// else replace the whole #right-col
			}						
  		},
  		complete: function()							// After loading success, put some effects
  		{
  			activateSubmitButton(ajaxHref);
			formAjax();

			selectTab();

			rightClickMenus();

			$("a[class='forceReload']").click(function(event){
				event.preventDefault();
				loadContent(getHash($(this).attr("href")), true, false);
			});

			$("#tree").sortable({
				delay: 50,
    			items: '.sortable-node'
  			});

			if(ajaxHref != '')
			{
				$('#left-col').removeAttr('style');
				$('#ajaxLoader').removeAttr('style');
				$('#ajaxLoader #loaderPic').removeAttr('style');
				$('#right-col').removeAttr('style').removeClass('homePanel');
			}

			$("#ajaxLoader").hide();
			$("#ajaxTabLoader").hide();
            boSearch();
  		}
	});
}

function checkSession()
{
    check = $.ajax({
        url:"?module=backoffice&action=AjaxCheckSession",
        async: false
    }).responseText;

    if(check == 'false')
    {
        showModal("?module=backoffice&action=login&href="+getHash(document.location.toString()), true);
        return false;
    }
    else
    {
        return true;
    }
}

/**
 * Reload the right column content
 */
function refreshRightCol()
{
	href = window.location.toString();

    if($('#nyroModalContent').html() != '' && $('#nyroModalContent').html() != null)
    {
         $('form.nyroModal').submit();
    }
    else
    {
        tabbed = isLoadingInTab(href);
        loadRightColContent(href, tabbed);
    }
}

/**
 * Open and display the right click context menu
 */
function rightClickMenus()
{
	$("#container").contextMenu({
		  menu: 'myMenu2'},function(action, element, el, pos)
		  {
			  	if($(element).hasClass("nyroModal"))
				{
					showModal("?module=backoffice&action=AjaxContext&href="+getHash($(element).attr("href")));
				}
				else
				{
				  	slideMenuToUp(action);						
				}
		  }
	);
}

/**
 * To delete a resized picture.
 */
function deletePicture(mediaId, lang, fileName)
{
	if(confirm(getLocale('medias.locales.deletePicture', {pictureName:fileName})) == true)
	{
		$.ajax({
			url:'?module=medias&action=AjaxDeletePicture&mediaId='+mediaId+'&lang='+lang+'&filename='+fileName,
			async: false,
			success: function(msg)
			{
				if(msg == "true")
				{
                    infoMessage(getLocale('website.locales.documentDeleted'));
					refreshRightCol();
					return false;
				}
			}
		});
	}
}

/**
 * Display modal window 
 * 
 * @param {String} href
 * @param {Boolean} noSessionCheck
 */
function showModal(href, noSessionCheck)
{
    if(noSessionCheck != true)
    {
        if(!checkSession()) return void(0);
    }
    
	$.nyroModalManual({
		url: href,
		minHeight: 105,
		minWidth: 300,
		modal: true,
		bgColor: '#CCCCCC',
		showBackground: function(elts, settings, callback){
			elts.bg.css("opacity", "0.8");
			callback();
		},
		showLoading: function(elts, settings, callback)
		{
			elts.loading.hide();
			callback();
		},
        endFillContent: function(elts, settings){
            if($('#modalContent').hasClass('withoutFooter'))
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
            else
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
        },
        endResize: function(elts, settings){           
            if($('#modalContent').hasClass('withoutFooter'))
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
            else
            {
                $('#modalContent').css('height', elts.contentWrapper.height()-101+'px');
            }
        },
		showContent: function(elts, settings, callback) {
		  elts.contentWrapper
		    .css({ // Reset the CSS at the start position
		      marginTop: (-100/2 + settings.marginScrollTop)+'px',
		      marginLeft: (-100/2 + settings.marginScrollLeft)+'px',
		      height: '30px',
		      width: '30px',
		      opacity: 0
		    })
		    .show()
		    .css({ // Set the width
		      width: settings.width+'px',
		      marginLeft: (settings.marginLeft)+'px',
		      height: settings.height+'px',
		      marginTop: (settings.marginTop)+'px',
		      opacity: 1
		    });
		    callback();
		},	
		showTransition: function(elts, settings, callback){
                    elts.loading
			.css({
				marginTop: elts.contentWrapper.css('marginTop'),
				marginLeft: elts.contentWrapper.css('marginLeft'),
				height: elts.contentWrapper.css('height'),
				width: elts.contentWrapper.width(),
				opacity: 1
			})
			.show();
			elts.contentWrapper.hide();
			callback();
		},
		hideTransition: function(elts, settings, callback){
			elts.loading.hide();
			elts.contentWrapper
			.css({
		      width: settings.width+'px',
		      marginLeft: (settings.marginLeft)+'px',
		      height: settings.height+'px',
		      marginTop: (settings.marginTop)+'px',
		      opacity: 1
			}).show();
			callback();	
		},
		endShowContent: function(elts, settings){
           if($('#exceptionContainer').html() != null)
           {
               $('#nyroModalContent').width(800);
               $('#nyroModalContent').parent().width(800);
               $('#nyroModalContent').parent().parent().width(800);
               $('<div style="width:100%; text-align:right"><a href="#" class="" onclick="$.nyroModalRemove();return false;">CLOSE</a></div>').prependTo('#exceptionContainer');
           }
           else
           {		
			   if($('#modalTabs').html() != null)
				{
					maxWidth = 0;
					maxHeight = 0;
					jQuery.each($('.modalTab').toArray(), function(i, val){
						if($('#'+val.id).width() > maxWidth)
						{
							maxWidth = $('#'+val.id).width();
						}
						if($('#'+val.id).height() > maxHeight)
						{
							maxHeight = $('#'+val.id).height();
						}
					});
					$('#modalContent').height('')
					$('#modalContent').css('min-width', maxWidth+20).height(maxHeight+50);
				}
				else
				{
					$('#modalContent').height('')
				}

                selectedTab = $('#modalTabs a.selected').attr('rel');

                if(selectedTab != null)
                {
                    $('.modalTab').hide();
                    $('#'+selectedTab).show();
                }

				$('#nyroModalContent').width($('#modalContent').width()+20);
				$('#nyroModalContent').parent().width($('#modalContent').width()+20);
				$('#nyroModalContent').parent().parent().width($('#modalContent').width()+20);

				formRedirect("nyroModal");
				initTinyMCE();
			}
		},
		hideContent: function(elts, settings, callback){
			elts.contentWrapper.hide();
			callback();
		},
		hideBackground: function(elts, settings, callback){
			elts.bg.hide();
			callback();
		}
	});
}

function formRedirect(param)
{
	$("#submitButton").focus();

    var previewUrl = $('#preview').html();

    if(previewUrl != null && previewUrl != '')
    {
        window.open(previewUrl);
    }
       
	var link = $("#formsuccess").html();
	if(link != null && link != "")
    {
		if(param == "nyroModal")
		{
			$.nyroModalRemove();
		}
		
		if(link == "currentPage" || link == "reloadMenu" || link == "refreshAll")
		{
			if(link == "currentPage")
			{
				refreshRightCol();
			}

            if(link == "refreshAll")
            {
                loadRightColContent(document.location.toString(), false);
            }
			
			reloadSlideMenuContent(document.location.toString());
		}
        else if(link == "blockEditRefresh")
        {
            reloadSlideMenuContent(document.location.toString());
            activatePageModificationsButtons();
        }
		else
		{
            if(link == "doNothing")
            {
                return void(0);
            }
            else
            {
                reloadSlideMenuContent(link);
                $.historyLoad(link, {refresh: true});
            }
		}
	}
}

function showAllRevisions()
{
	$("#revisionBlock").slideToggle("normal");
}

function viewOnlinePage(documentId)
{
	centeredPopup("../index.php?module=website&action=Preview&pageId="+documentId+"&revision=-1", "preview", 1024, 768);
}

 /**
 * Save the tab for a module
 */
var tabName = null;
var mName = null;
var moduleNameHref = null;
function getActiveTab(link)
{
	href = $('#moduleTabs a[class="selected"]').attr('href');
	if(href)
	{		
		ajaxHref = getHash(href);
		splitedHref = ajaxHref.split("/");
		moduleNameHref = splitedHref[1];
		splitNumber = $.ajax({url:"?module=backoffice&action=AjaxCheckTabName&href="+ajaxHref, async: false}).responseText;
		tabName = splitedHref[splitNumber];
	}
	
	if(mName != null && mName != moduleNameHref)
	{
		tabName = null;
	}
		
	ajaxLink = getHash(link);
	splitedLink = ajaxLink.split("/");
	splitNumber = $.ajax({url:"?module=backoffice&action=AjaxCheckTabName&href="+ajaxLink, async: false}).responseText;
	if(tabName != null && splitNumber != "null")
	{
		if(splitedHref.length == splitedLink.length)
		{
			splitedLink[splitNumber] = tabName;
		}
	}
	link = splitedLink.join("/");

	return link;
} 

/**
 * Switch des booléens
 */
function booleanSwitch(id,value,idElement)
{
	$("#editable_bool_"+idElement).load("index.php?module=backoffice&action=AjaxBooleanSwitch",{"id" : id, "value" : value});
}

  /**
   * generate the img balise for the icon
   * @param name
   * @param size
   * @param options
   * @param theme
   * @param context
   * @return img balise with icon path
   */
function getIcon(name, size, options, theme, context)
{
	 if(!size || size == "")
	 {
		 size = "16";
	 }
	 
	 if(!theme || theme == "")
	 {
		 theme = "default";
	 }
	 
	 if(!context || context == "")
	 {
		 context = "backend";
	 }
	 
	 if(!options || options == "")
	 {
		 options = "";
	 }
	 
	 if(size.length == 2)
	 {
		size = size + size;
	 }
	 	 
	 picture = urlSite+"/themes/"+theme+"/"+context+"/medias/icons/"+size+"/"+name;
	
	 return "<img src=\""+picture+"\" "+options+" />"
}
   
/*
 * Change the src path to change a picture
 */
function newSrc(imgPath, value)
{
    if(imgPath != null && imgPath != '')
    {
        var tab = imgPath.split("/");
        tab.splice(tab.length-1,1,value);
        imgPath = tab.join("/");
        return imgPath;
    }
    return value;
}

/**
 * Select correct tab
 */
function selectTab()
{
    if($("#sModuleTabs").length)
    {
        selectTabAction($("#moduleTabs a"), true);
        selectTabAction($("#sModuleTabs a"));
    }
    else
    {
        selectTabAction($("#moduleTabs a"));
    }
}

function selectTabAction(obj, setted)
{
	var els = $(obj).toArray();

	if(!setted)
    {
        setted = false;
    }

	jQuery.each(els, function(i, link) {
        if(setted == false)
        {
            $(link).removeClass("selected");
        }
        
		if(getHash($(link).attr('href')) == getHash(document.location.toString()))
		{
			setted = true;
			$(link).addClass("selected");
		}
	});
	
	if(setted == false)
	{
		$(els[0]).addClass("selected");
	}	
}

/**
 * Return on hash on given href.
 * 
 * @example http://www.myproject.com/bo/#/medias/edit/12 => /medias/edit/12
 * @param {String} href
 */
function getHash(href)
{
	return href.replace(/^.*#/, '');
}

function initTinyMCE()
{
    var frontTheme = $('#MCEtheme').val();
	tinyMCE.init({
        convert_urls : false,
		mode : "specific_textareas",
		editor_selector : "mceEditor",
		theme : "advanced",
		language : 'fr',
		plugins : 'pagizerFileManager, pagizerLinkManager, fullscreen, paste, table',
        extended_valid_elements : 'a[name|href|target|title|onclick|rel|class]',
        fullscreen_new_window : true,
        theme_advanced_resizing : true,
		theme_advanced_resize_horizontal : false,
		theme_advanced_toolbar_location : "top",
		theme_advanced_buttons1 : "undo,redo,pasteword,selectall,removeformat,cleanup,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect",
		theme_advanced_buttons2 : "fullscreen,|,tablecontrols ,|,bullist,numlist,|,outdent,indent,|,link,unlink,anchor,image,code,|,forecolor,backcolor",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_statusbar_location : "bottom",
		content_css : frontTheme,
        body_class : $('#MCEclass').val()
	});
}


/***************************************************************************
 *
 *                  GENERIC LIST
 *
 ***************************************************************************/


/**
 * Use to switch a publication status for any document
 * Switch only PUBLISHED <-> DRAFT
 */
function publicationStatusSwitch(docId, docLang, docModel)
{
    $("#sortable").children('tr').unbind('click');
    $.ajax
	({
		type: "POST",
		url: "?module=backoffice&action=AjaxSwitchPublicationStatus",
		data: {docId: docId, docLang: docLang, docModel: docModel},
		cache: false,
		success: function(msg)
		{
            classToRemove = msg == 'itemStatusButtonPUBLISHED' ? 'itemStatusButtonDRAFT' : 'itemStatusButtonPUBLISHED';
		    $("#docStatusPic_"+docId).removeClass(classToRemove).addClass(msg);
            documentListTable('#sortable');
		}
	});

    return false;
}

function pagination()
{
    $("#pagination a").click(function(event){
        event.preventDefault();
        $(this).unbind('click');
        numPage = $(this).attr("id") == "leftArrow" ? numPage - 1 : numPage + 1;
        genericFolderList();
    });

    $("#pagination select[name=nbDoc]").change(function(){
        nbDoc = parseInt($(this).val());
        genericFolderList();
    });

    $("#pagination select[name=nbPage]").change(function(){
        numPage = parseInt($(this).val());
        genericFolderList();
    });

    if(numPage <= 1)
    {
        $("#leftArrow").hide().unbind();
    }

    if(numPage >= nbPageTot)
    {
        $("#rightArrow").hide().unbind();
    }
}

function sort()
{
    $("table tr:first th a").click(function(){
        column = $(this).attr("name");
        order = $(this).attr("title");
        switch(order)
        {
            case "asc":
                order = "desc"
                break;
                
            case "desc":
                order = "asc";
                break;
        }

        genericFolderList();
    });
}

function search()
{
    $(window).keyup(function(event)
	{
		// Enter
		if(event.keyCode == 13)
        {
            execSearch();
        }
    });

    $(".searchBar input[type=text]").each(function(i){
        if($(this).val() != "")
        {
            var champ = $(this);
            $(this).after('<a />');
            $(this).next('a:first')
                        .addClass('itemButton itemDeleteButton')
                        .attr('href', 'javascript:void(0);')
                        .attr('title', getLocale("backoffice.locales.searchDelete"))
                        .click(function(){
                            champ.val("");
                            execSearch();
                        });
        }
    });
}

function execSearch()
{
    searchValues = $(".searchBar input[type=text]").serialize();
    $(window).unbind("keyup");
    if(searchValues != "")
    {
        genericFolderList();
    }
}

function genericFolderList()
{
    var ajaxHref = getHash(window.location.toString());

    var params = {
        numPage: window.numPage,
        nbDoc: window.nbDoc,
        column: window.column,
        order: window.order,
        searchValues: window.searchValues
    };

    $.ajax({
        url: "?module=backoffice&action=AjaxController&href="+ajaxHref+"&tabbed=true",
        cache: false,
        asyn: false,
        type: "POST",
        data: params,
        beforeSend: function(){
			$("#documentListTableLoader").show();
        },
        success: function(content)
        {
            $("#tabContent").replaceWith(content);
            $("#documentListTableLoader").hide();
        }
    });
}

/***************************************************************************
 * 
 * 					SLIDER MENU
 * 
 ***************************************************************************/

/**
 * Get the slider menu actions
 */
function sliderMenu()
{
	$(".slideMenuItem").hover(function(){
            if($(this).children("span.slideMenuItemButtons:first").html()) {
		$(this).children("span.slideMenuItemButtons:first").show();
            }
	}, function(){
		$(this).children("span.slideMenuItemButtons:first").hide();
	});
	
	$(".slideMenuItemButtons").hover(function(){
        if(!$(this).parent(".slideMenuItem:first").hasClass('selected'))
        {
            $(this).parent(".slideMenuItem:first").addClass("slidingMenuHover");
        }
	},function(){
        var parent = $(this).parent(".slideMenuItem:first");
        if(!parent.hasClass('selected'))
        {
            $(this).parent(".slideMenuItem:first").removeClass("slidingMenuHover");
        }
	})
	
	$(".slidingMenu").sortable({
		opacity: 0.6,
		items: '.moveable',
		axis: 'y',
		sort: function(event, ui){
			$(".slidingMenu a").css("cursor", "row-resize");
		},
		stop: function(event, ui){
			$(".slidingMenu a").css("cursor", "pointer");
		},
		update: function(event, ui) {
			$.ajax({
				url: '?module=backoffice&action=sliderMenuItemSort&href='+getHash(location.href)+'&'+$(this).sortable('serialize')
			})
		}
	});

    slidingMenuUpDown();
}

function slidingMenuUpDown()
{
    $('.slideMenu').css('top', '0px');

    if(($('#left-col').height()-119) < ($('#slideMenuContainer .slide-menu-left').height()))
    {
        $('.menuSlidingUpDown').show();

        $('#menuDown').unbind("mousedown");
        $('#menuDown').mousedown(function()
        {
            var t = parseInt($('.slideMenu').css('top').replace('px', ''));
            var diff = ($('#left-col').height()-119) - $('#slideMenuContainer .slide-menu-left').height();
            $(this).addClass('menuSlidingUpDownClick');
            if(t > diff)
            {
                $('.slideMenu').css('top', t-16+'px');
            }
        }).mouseup(function(){
            $(this).removeClass('menuSlidingUpDownClick');
        });

        $('#menuUp').unbind("mousedown");
        $('#menuUp').mousedown(function()
        {
            $(this).addClass('menuSlidingUpDownClick');
            var t = parseInt($('.slideMenu').css('top').replace('px', ''));
            if(t < 0)
            {
                $('.slideMenu').css('top', (t+16)+'px');
            }
        }).mouseup(function(){
            $(this).removeClass('menuSlidingUpDownClick');
        });
    }
    else
    {
        $('.menuSlidingUpDown').hide();
    }
}

/**
 * Slide from right to left - one level up
 * @param {String} href
 */
function slideMenuToUp(href)
{
    $.ajax({
        url: 'index.php?module=backoffice&action=block_sliderMenu',
        data: {href: getHash(href)},
        success: function(result)
        {
            $("#slideMenuContainer .slide-menu-right").html(result);
        },
        complete: function()
        {
            $("#slideMenuContainer").css({marginLeft:0});
            $("#slideMenuContainer").animate(
            {marginLeft:"-250px"},
            200,
            'swing',
            function(){
                $("#slideMenuContainer .slide-menu-left").html($("#slideMenuContainer .slide-menu-right").html());
                $("#slideMenuContainer").css({marginLeft:"0px"});
                $.historyLoad(getHash(href), {onlyLoadRightCol: true, loadInTab: false});
                sliderMenu();
            });
        }
    });
}

/**
 * Slide from left to right - history back
 * @param {String} href
 */
function slideMenuToDown(href)
{
	$("#slideMenuContainer .slide-menu-right").html($("#slideMenuContainer .slide-menu-left").html());
	
	$("#slideMenuContainer").css({marginLeft:"-250px"});
    $.ajax({
        url: 'index.php?module=backoffice&action=block_sliderMenu',
        data: {href: getHash(href)},
        success: function(result){
            $("#slideMenuContainer .slide-menu-left").html(result);
        },
        complete: function(){
            $("#slideMenuContainer").animate(
            {marginLeft:"0px"},
            200,
            'swing',
            function()
            {
                $("#slideMenuContainer .slide-menu-right").html("");
                $.historyLoad(getHash(href), {onlyLoadRightCol: true, loadInTab: false});
                sliderMenu();
            });
        }
    })
}

function reloadSlideMenuContent(href)
{
	$("#slideMenuContainer .slide-menu-left").load('?module=backoffice&action=block_sliderMenu&href='+getHash(href), function(){
		sliderMenu();
	});
}

/***************************************************************************
 *
 * 					BO SEARCH MANAGEMENT
 *
 ***************************************************************************/

function boSearch()
{
    $('.boSearch_field').flushCache();
    $('.boSearch_field').unbind();

    $('.boSearch_field').val(getLocale('backoffice.locales.searchField')).click(function(){
        $(this).val('');
    }).blur();

    $('.boSearch_field').autocomplete(
        '?module=backoffice&action=AjaxBoSearch',
        {
            minChars:1,
            cacheLength:10,
            width: 158,
            scrollHeight: 400,
            formatItem:function(data, i, n, item) {
                return data[0];
            },
            extraParams:{
                moduleName:getHash(document.location.toString())
            }
        }
    ).result(function(event, item) {
        $.historyLoad(item[1], {refresh:true});

        if(item[2] != null && item[2] != '' && item[2] != 'undefined')
        {
            showModal('?module=backoffice&action=AjaxContext&href='+item[2]);
        }
    })
}

/***************************************************************************
 * 
 * 					USERS MANAGEMENT
 * 
 ***************************************************************************/
 
function reloadSuRights()
{
	$.getScript("?module=rights&action=AjaxRefreshSuRights",
		function(value)
		{
			infoMessage(value);
		}
	);
}

 function changeGroupRights(group, module, bool)
 {
	$.ajax
	({
		type: "POST",
		url: "?module=rights&action=AjaxChangeRights",
		data: "&groupId="+group+"&rightModule="+module+"&bool="+bool,
		success: function(authorized)
		{
			
			 $("#tab_"+module+" img[class=icon16]").each(function(i){
				var iCheck = newSrc(this.src, "active_right.png");
				var iDelete = newSrc(this.src, "unactive_right.png");
				
				 if(authorized == "true")
				 {
					 this.src = iCheck;
				 }
				 
				 if(authorized == "false")
				 {
					 this.src = iDelete;
				 }
				 
				 if(authorized == "mid")
				 {
					 this.src =  this.src == iDelete ? iCheck : iDelete;
				 }
			 });
		}
	});
 }
 
 /**
  * Add or delete a right
  *	@param group
  * @param right
  */
function changeRights(group, right)
{
	$.ajax
	({
		type: "POST",
		url: "index.php?module=rights&action=AjaxChangeRights",
		data: "&groupId="+group+"&right="+right,
		success: function(authorized)
		{
            var icon = 'active_right.png';
			if(authorized == "false")
			{
				icon = 'unactive_right.png';
			}

            $("#rights_Rights_"+right+"_acces").html(getIcon(icon,'16','class="icon16"'));
		}
	});
}

function changeDocRights(group, module, docId, docLang, right, blockId)
{
    $("#ajaxTabLoader").show();

	$.ajax
	({
		type: "POST",
		url: "index.php?module=rights&action=AjaxChangeDocRights",
		data: {groupId: group, moduleRight: module, docId: docId, docLang: docLang, rule: right, blockId: blockId},
        dataType: 'json',
		success: function(tab)
		{
            $.each(tab, function(i, data){
                $.each(data.rights, function(j, item){
                    var block = (data.blockId ? "_"+data.blockId : "");
                    
                    $id = $("#"+data.documentId+"_"+data.documentLang+"_"+data.module+"_"+j+block);
                    var src = $id.children('img').attr('src');
                    var icon = "";

                    switch(item)
                    {
                        case '0':
                            icon = "unactive_right.png";
                        break;
                        case '1':
                            icon = "active_right.png";
                        break;
                        case '2':
                            icon = "active_right2.png";
                        break;
                        case '3':
                            icon = "lockedblock.png";
                        break;
                    }

                    $id.children('img').attr('src', newSrc(src, icon));
                });
            });

            $("#ajaxTabLoader").hide();
		}
	});
}


/*
 * Add a picture to a news or link media
 */
function saveImg(imgId)
{
    $("#pictureId").val(imgId);
    $('.removeLinkedImage').show();
    $.ajax({
        url: "?module=backoffice&action=block_GenericPictureSelect",
        type: "POST",
        data: {docId: imgId, mode: 1},
        success: function(msg)
        {
            $("#picSelect").html(msg);
        }
    });
}

/**
 * Link a media to another media
 */
function linkImg(imgId, fileName, action)
{
    if(action == "unlink" && confirm("Délier le médias '"+fileName+"' ?") == false)
    {
        return false;
    }

    var url = $("#mediaEditUrl").text();

    $.ajax({
        url: "?module=backoffice&action=AjaxContext&href="+url,
        type: "POST",
        data: {linkedDocId: imgId, linkAction: action},
        complete: function()
        {
            if($('#nyroModalContent').html() != '')
            {
                $('form.nyroModal').submit();
            }
        }
    });
}

function getUrl(args)
{
    var url;
    $.ajax({
        url: "index.php?module=backoffice&action=AjaxGetUrl",
        async: false,
        data: args,
        success: function(msg)
        {
            url = msg;
        }
    });
    return url;
}

/***************************************************************************
 * 
 * 					LIVE QUERY FUNCTIONS (http://docs.jquery.com/Plugins/livequery)
 * 
 ***************************************************************************/
 
/**
 * Use the liveQuery jQuery plugin.
 * This will add functionnality to new elements or loaded elements (by ajax per example)
 */
function liveQuery()
{
	liveQueryTooltips();
	liveQueryHighLightInputs();
	liveQueryContextMenu();
	liveQueryModuleTabs();
    liveQueryModalTabs();
	liveQueryLinks();
	liveQuerySliderMenu();
	liveQueryCheckAll();
    liveQueryFileUpload();
    liveQueryFormRedirect();
    liveQueryAddImgNews();
    liveQueryMainMenu();
    liveQuerySliderMenuContext();
    rollover();
    boSearch();
    editBlockLabel();
}

function editBlockLabel()
{
    $('dl.block span.editable').live('click',function(event)
    {
        showModal('?module=website&action=block_modal_EditBlockLabel&id='+$(this).attr('id'));
    });
}

function rollover()
{
    $('.rolloverButton').hover(function()
    {
        $(this).addClass('active');
        $('.rollover').show();
    }, function (){
        $(this).removeClass('active');
        $('.rollover').hide();
    }
    );

    $('.rollover').hover(function()
    {
        $('.rolloverButton').addClass('active');
        $(this).show();
    }, function (){
        $('.rolloverButton').removeClass('active');
        $(this).hide();
    }
    );
}

function liveQueryMainMenu()
{
    $('#mainMenu a').live('click',function(event)
    {
        event.preventDefault();
        
        $("#ajaxLoader").show();
        params = document.location.hash.split("/");
        linkId = '#'+params[1]+'Link';
        $(linkId).attr('href', document.location.toString());

        $('#mainMenu a.selected').removeClass('selected');
        $(this).addClass('selected');

        $.historyLoad(getHash($(this).attr('href')), {loadInTab: false});
    });
}

var actionAddImg = "tinyMce";
function liveQueryAddImgNews()
{
    /* To link a media to a news */
	$(".addImg").live('click',function(event){
        event.preventDefault();
        var url = urlSite+"/js/lib/tiny_mce/plugins/pagizerFileManager/index.php";
        urlImg = url;
        vars = $("#image").children("img").attr("rel");

        if(vars)
        {
            urlImg = urlImg+"#";
            urlImg = urlImg+vars;
        }

        actionAddImg = $(this).hasClass("media") ? "media" : "image";
		centeredPopup(urlImg, "Medias", "980", "600", "yes");
	});

    $('.removeLinkedImage').live('click',function(){
        $('#picSelect').html("");
        $('#pictureId').val('');
        $('.removeLinkedImage').hide();
    });
}

function liveQueryCheckAll()
{
	$("input.checkAll").live('click', function()
	{
		var checked_status = this.checked;
		$("input[@type=checkbox].select").each(function()
		{
            if(this.disabled == false)
            {
                this.checked = checked_status;
            }
		});
	});

	$("input[type=checkbox].select").live('click', function()
    {
		var result = $("#selectResult").empty();
        var authorized = true;
		var i = 0;

		$("#result").livequery(function(){
			$("#selectResult").append($(this).text()+"&saveButton=1");
		});
		
		$("input[type=checkbox].select").each(function()
		{		
			if(this.checked && $(this).hasClass("checkAll") == false)
			{
				result.append("&row["+ i +"]=" + $(this).val());
                if($(this).parents("tr").find("span.listButtons").children("a.itemDeleteButton").length == 0)
                {
                    authorized = false;
                }
				i++;
			}
		});

		if(i > 0)
		{
			$("#selectedelements").text(i + " élément(s) sélectionné(s)");
            $("a.nyroModalResult").addClass("active");
            if(authorized == false)
            {
                $("a.delete").removeClass("active");
            }
		}
		else
		{
			$("#selectedelements").empty();
			$("a.nyroModalResult").removeClass("active");
		}
	});

    $("#sortable").livequery(function(){
       $(this).sortable({
            opacity: 0.6,
            items: 'tr',
            axis: 'y',
            zindex: 100,
            tolerance: 'pointer',
            start: function(event, ui){
                $(this).css("cursor", "row-resize");
            },
            stop: function(event, ui){
                $(this).css("cursor", "default");
            },
            update: function(event, ui)
            {
                var rows = "";
                $("#sortable tr").each(function(i){
                    var index = this.id;
                    ind = i+1;
                    rows = rows+"&row["+ind+"]=" + index;
                });

                $.ajax({
                    url: '?module=backoffice&action=AjaxSortItems&docLang=' + $("#folderLang").text() + '&docId=' + $("#folderId").text() + '&' + rows
                })
            }
        });

        documentListTable('#sortable');
    });

	$("a.nyroModalResult").live('click', function(){
		if($(this).hasClass("active"))
		{
			var link = $(this).attr("href") + $("#selectResult").text();
			showModal(getHash(link).substr(1));
		}
		return false;
	});
}

jQuery.fn.alternateRowColors = function() {
  $('tr:odd', this).removeClass('even').addClass('odd');
  $('tr:even', this).removeClass('odd').addClass('even');
  return this;
};

function documentListTable(id)
{
        $(id).alternateRowColors();

        $(id).children('tr').hover(function(){
            $(this).find('.listButtons').css('visibility', 'visible');
            link = $(this).find('.defaultAction').attr('href');
            if(link != null && link != '') $(this).find('td').css('cursor', 'pointer');

            $(this).find('.openNewWindow').unbind('click').click(function(event){
                event.preventDefault();
                slideMenuToUp(getActiveTab(getHash($(this).attr('href'))));
            });

            $(this).find('.openInTab').unbind('click').click(function(event){
                event.preventDefault();
                loadContent(link, {loadInTab:true});
            });

            $(this).children('td').each(function(){
                if(!$(this).children('span').hasClass('listButtons') && $(this).children('input').attr('type')!='checkbox' && !$(this).children('a').hasClass('publicationSwitchButton'))
                {
                    $(this).unbind('click');
                        $(this).click(function(){
                            if(link != null && link != '')
                            {
                                if($(this).parent().find('.defaultAction').hasClass('openNewWindow'))
                                {
                                    slideMenuToUp(getActiveTab(getHash(link)));
                                }
                                else if($(this).parent().find('.defaultAction').hasClass('nyroModal'))
                                {
                                    showModal('?module=backoffice&action=AjaxContext&href='+getHash(link));
                                }
                                else if($(this).parent().find('.defaultAction').hasClass('openInTab'))
                                {
                                    loadContent(link, {loadInTab:true});
                                }
                                else
                                {
                                    loadContent(link);
                                }
                            }
                        });
                }
            });
        }, function(){
            $(this).children('td').children('.listButtons').css('visibility', 'hidden');
        });
        $(id).children('tr').mouseout(function(){
            $(this).children('td').css('background-color', '');
        });

}

/**
 * Display tooltips to input, select elements or elements with class toolTip
 */
function liveQueryTooltips()
{
	$('.toolTip:not(img)').livequery(function()
	{        
		$(this).tooltip(
		{ 
		    track: false,
		    delay: 1000,
		    showURL: false, 
		    fixPNG: true, 
		    showBody: " - ", 
		    extraClass: "fancy", 
		    top: -5, 
		    left: 5
		})
	});

    $('img.toolTip').livequery(function()
	{
        $(this).tooltip(
		{ 
		    track: false,
		    delay: 0, 
		    showURL: false, 
		    fixPNG: true, 
		    showBody: " - ", 
		    extraClass: "fancy", 
		    top: -5, 
		    left: 5
		})
    });
}

/**
 * Hilight text inputs when selected
 */
function liveQueryHighLightInputs()
{
    $('.documentListItems').livequery(function(){
        documentListTable('.documentListItems');
    });

    $('.documentListItems input, .documentListItems a, #sortable input').livequery(function(){
        $(this).hover(function(){
            $("#sortable, .documentListItems").children('tr').unbind('click');
        },function(){
            documentListTable('.documentListItems, #sortable');
        });
    });

	$('input.dateInput').livequery(function(){
        $(this).datepicker({duration: 'fast'});
    },function(){
        $(this).datepicker('destroy');
    });
}

/**
 * Catch the click on context menu
 */
function liveQueryContextMenu()
{
	$("#contextMenu a, .rollover a.modal").live('click', function(event){
		// Catch the click
		event.preventDefault();
		showModal("?module=backoffice&action=AjaxContext&href="+getHash($(this).attr("href")));		
	});

    $('.contextMenuButton').live('mouseover',function(){
        $('#contextMenuLabel').text($(this).find('a').attr('rel'));
        $('#contextMenuLabel').show();
    }).live('mouseout', function(){
        $('#contextMenuLabel').text('');
        $('#contextMenuLabel').hide();
    });

}

/**
 * Manage tabs 
 */
function liveQueryModuleTabs()
{
	$("#moduleTabs a").live('click', function(event){
		event.preventDefault();
		if($(this).attr("href") != "" && $(this).attr("href") != "#")
		{
            $("#ajaxTabLoader").show();
		    $("#moduleTabs a.selected").removeClass("selected");
		    $(this).addClass("selected");
            $.historyLoad(getHash($(this).attr("href"),{onlyLoadRightCol: true, loadInTab: true}));
		}
	});

	$("#sModuleTabs a").live('click', function(event){
		event.preventDefault();
		if($(this).attr("href") != "" && $(this).attr("href") != "#")
		{
            $("#ajaxTabLoader").show();
		    $("#sModuleTabs a.selected").removeClass("selected");
		    $(this).addClass("selected");
            $.historyLoad(getHash($(this).attr("href"),{onlyLoadRightCol: true, loadInTab: true}));
		}
	});
}

function liveQueryModalTabs()
{   
    $("#modalTabs a").live('click', function(event){
		event.preventDefault();
		if($(this).attr("rel") != "")
		{
            $("#modalTabs a").removeClass('selected');
            $(this).addClass('selected');
            $('.modalTab').hide();
            $('#'+$(this).attr("rel")).show();
		}
	});
}

/**
 * Catch click on links in bo
 */
function liveQueryLinks()
{
	$("#mainframe div[id!='moduleTabs'] > a[rel='history'][class!='nyroModal']").live('click', function(event){
		loadContent();
		return false;
	});

    $("a.reload").live('click', function(event){
        event.preventDefault();
        $.historyLoad($(this).attr('href'), {refresh: true});
    });

    $("a.loadInTab").live('click', function(event){
        event.preventDefault();
        $.historyLoad($(this).attr('href'), {loadInTab:true});
    });

    $("ul.saveButtons li a").live('click', function(event){
        if(!$(this).hasClass('active'))
        {
            event.preventDefault();
        }
        if($(this).hasClass('refreshTab'))
        {
            event.preventDefault();
            $.historyLoad(getHash(document.location.toString()), {loadInTab:true});
        }

        if($(this).hasClass('ajax'))
        {
            event.preventDefault();
            $.ajax({
                url: $(this).attr('href'),
                async: true,
                success: function(res)
                {
                    if(res == 'reloadTab')
                    {
                        $.historyLoad(getHash(document.location.toString()), {loadInTab:true});
                    }
                    else if(res == '')
                    {
                        return void(0);
                    }
                    else
                    {
                        loadRightColContent(res, true);
                    }
                }
            });
        }
    });
	
	$("a.nyroModal").live('click', function(event){
		event.preventDefault();
		if(!$(this).hasClass("deactivated"))
		{
			showModal("?module=backoffice&action=AjaxContext&href="+getHash(this.href));
		}
		return false;
	});	
}

/**
 * Catch click on slider menu items
 */
function liveQuerySliderMenu()
{
	$(".slideMenuItem a.node").live('click', function(event){
		if(!$(this).hasClass("selected"))
		{			
			event.preventDefault();
			
			var link = getHash($(this).attr('href'));

            if($(this).hasClass("noslide"))
            {
                $(".slidingMenu a.selected").removeClass("selected");
                $(this).addClass("selected");
            }
					
			//Load right column content
			if (link != "#" && link != "")
            {
                $("#ajaxLoader").show();

				//Keep the active tab - tabName is a global variable
				link = getActiveTab(link);
	
				// Slide menu to upper level
				if ($(this).hasClass("more"))
                {
					slideMenuToUp(link);
				}
				
				// Slide menu to lower level
				if ($(this).hasClass("expanded"))
                {
					if ($(this).hasClass("noslide"))
                    {
						$.historyLoad(getHash(link), {onlyLoadRightCol: true, loadInTab: false});
					}
					else
                    {
						slideMenuToDown(link);
					}
				}
				else
				{
					if ($(this).hasClass("noslide"))
                    {
                        $.historyLoad(getHash(link), {onlyLoadRightCol: true, loadInTab: false});
					}					
				}
			}
		}
	});
}

function liveQueryFileUpload()
{  
  $('.fileUpload').livequery(function(){
        $(this).ajaxForm({
            target: '#right-col'
        });
  });
}

function liveQueryFormRedirect()
{
    $("form.formRedirect").livequery(function()
	{
		formRedirect("form");
	});
}

function liveQuerySliderMenuContext()
{
    $('.slideMenuAddMenu').livequery(function()
    {
        $(this).hover(function(){
            $('#slideMenuHoverContext').html($('#sliderMenuContextMenu').html());

            var pos = $(this).offset();
            var top = pos.top - 2 + "px";
            
            $('#slideMenuHoverContext').css({
                display: 'block',
                position: 'absolute',
                zIndex: 10,
                top: top
            });

        }, function(){
            $('#slideMenuHoverContext').hide();
        });

        $('#slideMenuHoverContext').hover(function(){
            $('#slideMenuHoverContext').show();
        }, function(){
            $('#slideMenuHoverContext').hide();
        });

    });
}


/***************************************************************************
 * 
 * 					ACTIONS ONLOAD
 * 
 ***************************************************************************/

function historyLoadContent(href, options)
{
    if(options != 'undefined' && options != null)
    {
        loadContent(href, options);
    }
    else
    {
        loadContent(href, {refresh: true});
    }
}

$(document).ready(function()
{

	$.historyInit(loadContent);

	$(this).ajaxStart(function(){
		$('#contextualHelp').show();
	}).ajaxSuccess(function(){
		$('#contextualHelp').hide();
	}).ajaxError(function(event, request, settings){
        alert(getLocale('backoffice.errors.ajax'));
	});

    $(window).resize(function(){slidingMenuUpDown()});

	liveQuery();
});
